#!/bin/bash
#
# Copyright (c) 2015 Red Hat, Inc.
#
# Author: Loic Dachary <loic@dachary.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
### BEGIN INIT INFO
# Provides:        teuthology
# Required-Start:  $network $remote_fs $syslog beanstalkd nginx
# Required-Stop:   $network $remote_fs $syslog
# Default-Start:   2 3 4 5
# Default-Stop:
# Short-Description: Start teuthology
### END INIT INFO

cd /home/ubuntu

source /etc/default/teuthology

user=${TEUTHOLOGY_USERNAME:-ubuntu}

export HOME=/home/$user

function worker_pidfile() {
    echo /var/run/teuthology-worker.$1.pid
}
function worker_logfile() {
    echo /var/log/teuthology.${1}.log
}

function stop_worker() {
    wnum=$1
    wpidfile=$(worker_pidfile $wnum)
    if [[ -f $wpidfile ]] ; then
        wpid=$(cat $wpidfile)
        echo Killing worker $wnum with pid=$wpid...
        pkill -P $wpid
        pkill $wpid
        rm -f $wpidfile
    fi
}

function stop_workers() {
    for i in $(seq 1 $NWORKERS) ; do
        stop_worker $i
    done
}

function start_worker() {
    local wlogfile=$1
    local wpidfile=$2
    mkdir -p /tmp/log && chown $user /tmp/log
    su - -c "
cd /home/$user
source openrc.sh
cd teuthology
export LC_ALL=C
virtualenv/bin/teuthology-worker --tube openstack -l /tmp/log --archive-dir /usr/share/nginx/html
" $user > $wlogfile 2>&1 & {
        echo $! > $wpidfile
        echo "Started worker with pid=$! see log $wlogfile"
    }
}

function rkill() {
    local pid=$1
    for i in $(pgrep -P $pid) ; do
        rkill $i
    done
    echo Killing process $pid
    kill -9 $pid
}
function status_process() {
    local name=$1
    local pidf=$2
    [[ -f $pidf ]] && {
        PID=$(cat $pidf)
        STATUS=$(ps aux --no-headers -q $PID 2>&1 > /dev/null && echo running || echo dead)
        echo $name PID:$PID STATUS:$STATUS
    }
}

function stop_process() {
    local pidfile=$1
    [[ -f $pidfile ]] && {
        local pid=$(cat $pidfile)
        rkill $pid
        ps aux --no-headers -q $pid 2>&1 > /dev/null || rm $pidfile
    }
}

function start_workers() {
    for i in $(seq 1 $NWORKERS) ; do
        local wpidfile=$(worker_pidfile $i)
        local wlogfile=$(worker_logfile $i)
        [[ -f $wpidfile ]] && {
            local wpid=$(cat $wpidfile)
            ps aux --no-headers -q $wpid 2>&1 > /dev/null && {
                echo Worker $i is already running with process $wpid
                continue
            }
        }
        start_worker $wlogfile $wpidfile
    done
}

case $1 in
        start-workers)
            start_workers
            ;;
        status-workers|list-workers)
            for i in $(ls /var/run | grep teuthology-worker | sort) ; do
                WORKER=${i##teuthology-worker.}
                WORKER=${WORKER%%.pid}
                status_process "worker $WORKER" /var/run/$i
            done
            ;;
        stop-workers)
            echo Stopping workers
            stop_workers
            ;;
        stop-worker)
            stop_worker $2
            ;;
        restart-workers)
            $0 stop-workers
            $1 start-workers
            ;;
        status-pulpito)
            status_process pulpito /var/run/pulpito.pid
            ;;
        start-pulpito)
            su - -c "cd /home/$user/pulpito ; virtualenv/bin/python run.py" $user  > /var/log/pulpito.log 2>&1 & \
            echo $! > /var/run/pulpito.pid
            ;;
        stop-pulpito)
            echo Stopping pulpito
            stop_process /var/run/pulpito.pid
            ;;
        status-paddles)
            status_process paddles /var/run/paddles.pid
            ;;
        start-paddles)
            su - -c "cd /home/$user/paddles ; virtualenv/bin/pecan serve config.py" $user  > /var/log/paddles.log 2>&1 &
            echo $! > /var/run/paddles.pid
            ;;
        stop-paddles)
            echo Stopping paddles
            stop_process /var/run/paddles.pid
            ;;
        start)
                /etc/init.d/beanstalkd start
                $0 start-paddles
                $0 start-pulpito
                sleep 3
                (
                   cd /home/$user
                   source openrc.sh
                   cd teuthology
                   . virtualenv/bin/activate
                   teuthology-lock --list-targets --owner scheduled_$user@teuthology > /tmp/t
                   if test -s /tmp/t && ! grep -qq 'targets: {}' /tmp/t ; then
		       teuthology-lock --unlock -t /tmp/t --owner scheduled_$user@teuthology
		   fi
                   start_workers
                )
                ;;
        stop)
                #pkill -f 'pecan serve'
                #pkill -f 'python run.py'
                #pkill -f 'teuthology-worker'
                $0 stop-pulpito
                $0 stop-paddles
                $0 stop-workers
                pkill -f 'ansible'
                /etc/init.d/beanstalkd stop
                source /home/$user/teuthology/virtualenv/bin/activate
                source /home/$user/openrc.sh
		for dev in eth0 ens3 ; do
		    ip=$(ip a show dev $dev 2>/dev/null | sed -n "s:.*inet \(.*\)/.*:\1:p")
		    test "$ip" && break
		done
                openstack server list --long -f json --name target | \
                    jq ".[] | select(.Properties | contains(\"ownedby='$ip'\")) | .ID" | \
                    xargs --no-run-if-empty --max-args 1 -P20 openstack server delete --wait
                openstack server list --long -f json --name ceph- | \
                    jq ".[] | select(.Properties | contains(\"ownedby='$ip'\")) | .ID" | \
                    xargs --no-run-if-empty --max-args 1 -P20 openstack server delete --wait
                openstack volume list --long -f json | \
                    jq ".[] | select(.Properties | contains(\"ownedby='$ip'\")) | .ID" | \
                    xargs --no-run-if-empty --max-args 1 -P20 openstack volume delete
                perl -pi -e 's/.*gitbuilder_host.*/gitbuilder_host: gitbuilder.ceph.com/' /home/$user/.teuthology.yaml
                rm -fr /home/$user/src/*
                mv /tmp/stampsdir /tmp/stampsdir.old
                mkdir /tmp/stampsdir
                chown $user /tmp/stampsdir
                if test -f /tmp/stampsdir.old/packages-repository ; then
                    mv /tmp/stampsdir.old/*packages-repository* /tmp/stampsdir
                fi
                rm -fr /tmp/stampsdir.old
                ;;
        restart)
                $0 stop
                $0 start
                ;;
        *)
esac
